package com.aerozhonghuan.logisticsmall.modules.home;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.DB.DBAdapter;
import com.aerozhonghuan.logisticsmall.framework.base.TitlebarActivity;
import com.aerozhonghuan.logisticsmall.modules.common.MainActivity;
import com.aerozhonghuan.logisticsmall.modules.common.entity.GoodsObject;
import com.aerozhonghuan.logisticsmall.modules.common.entity.ProductImg;
import com.aerozhonghuan.logisticsmall.modules.common.event.TabNumberChangedEvent;
import com.aerozhonghuan.logisticsmall.modules.home.beans.ProductFavorite;
import com.aerozhonghuan.logisticsmall.modules.home.logic.HomePageInfoRequest;
import com.aerozhonghuan.logisticsmall.modules.home.search.SearchProductActivity;
import com.aerozhonghuan.logisticsmall.modules.sort.SortFragment;
import com.aerozhonghuan.logisticsmall.utils.CommunityTool;
import com.aerozhonghuan.logisticsmall.utils.CommunityUtils;
import com.aerozhonghuan.logisticsmall.utils.StatisticsConstant;
import com.aerozhonghuan.logisticsmall.utils.StatusBarUtil;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ChenLin on 2019/5/22 10:51.Email&WeChat:7877409@163.com
 */
public class GoodsDetailsActivity extends TitlebarActivity implements
        View.OnClickListener, AddProductToGouwuche, ViewPager.OnPageChangeListener, View.OnLayoutChangeListener {

    public static final String TAG = GoodsDetailsActivity.class.getSimpleName();
    private GoodsObject mProduct;
    private TextView mFavoritView;
    private TextView mProductTitleView;
    private TextView mProductPriceView;
    private TextView mOriginalPrice;
    private LinearLayout mSelectsizeLayout;

    private TextView mProductUnit;
    private TextView mProductBrand;
    private TextView mProductAddress;
    private TextView mProductDiscription;

    private DBAdapter mDbAdapter;
    private ArrayList<Drawable> mDrawables = new ArrayList<Drawable>();
    private TextView mGouwucheSize;
    private AlertDialog mDialog;
    private Dialog mLoadDataDialog;
    private Animation mScaleBigAnim;

    private TextView mButSizeTxView;
    private List<ProductImg> mProductImgIds;
    private ViewPager mImgsPager;
    private List<ImageView> mListImageViews;
    private int mProductFavoriteId;
    private float price = 0;
    private ViewGroup mViewGroup;
    private ImageView[] mPointsViews;
    private ChangeProductGouwucheNum iChangeProductGouwucheNum;
    private View mRootView;
    private TextView mNoStockView;
    private LayoutInflater inflater;
    private View view;
    private FrameLayout container;
    private RequestOptions options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setLightStatusBar(this, true);
        mDbAdapter = new DBAdapter(this);
        if (savedInstanceState == null) {
            container = (FrameLayout) findViewById(R.id.container1);
            inflater = LayoutInflater.from(getContext());
            view = inflater.inflate(R.layout.goods_details_activity, null);
            container.addView(view);
            initView();
        }
    }

    private void initView() {
        mProductTitleView = (TextView) view.findViewById(R.id.product_title);
        mProductPriceView = (TextView) view.findViewById(R.id.product_price);
        mOriginalPrice = (TextView) view.findViewById(R.id.original_price);
        mSelectsizeLayout = (LinearLayout) view.findViewById(R.id.selectsize_layout);
        view.findViewById(R.id.add_btn).setOnClickListener(this);
        view.findViewById(R.id.min_btn).setOnClickListener(this);
        mButSizeTxView = (TextView) view.findViewById(R.id.buy_size_text);
        mNoStockView = (TextView) view.findViewById(R.id.no_stock);
        mRootView = (View) view.findViewById(R.id.root_view);
        mRootView.addOnLayoutChangeListener(this);
        mProductUnit = (TextView) view.findViewById(R.id.product_unit);
        mProductBrand = (TextView) view.findViewById(R.id.product_brand);
        mProductAddress = (TextView) view.findViewById(R.id.product_address);
        mProductDiscription = (TextView) view.findViewById(R.id.product_description);

        mImgsPager = (ViewPager) view.findViewById(R.id.imgs_viewpager);
        mImgsPager.setOnPageChangeListener(this);
        mViewGroup = (ViewGroup) view.findViewById(R.id.view_group);
        mListImageViews = new ArrayList<ImageView>();
        mLoadDataDialog = CommunityTool.getInstance().createLoadingDialog(this, "");
        mScaleBigAnim = AnimationUtils.loadAnimation(this, R.anim.favorit_anim);
        options = new RequestOptions().placeholder(R.mipmap.ic_placehodler).error(R.mipmap.ic_placehodler);
        Intent intent = getIntent();
        String from = intent.getStringExtra("from");
        if (!TextUtils.isEmpty(from) && from.equals("product_category_activity")) {
            iChangeProductGouwucheNum = SortFragment.sSortFragment;
        } else if (!TextUtils.isEmpty(from) && from.equals("search_product_activity")) {
            iChangeProductGouwucheNum = SearchProductActivity.mSearchProductActivity;
        } else if (!TextUtils.isEmpty(from) && from.equals("my_often_buy_activity")) {
            iChangeProductGouwucheNum = MyOftenBuyActivity.sMyOftenBuyActivity;
        }
        int pvsid = intent.getIntExtra("pvsid", 0);
        if (pvsid != 0) {
            queryProductInfoForId(pvsid);
        }
    }

    private void queryProductInfoForId(int pvsid) {
        //请求商品详情（app-good/detail.json）
        HomePageInfoRequest.detail(pvsid + "", this, new ProgressDialogIndicator(this), new CommonCallback<GoodsObject>() {
            @Override
            public void onSuccess(GoodsObject messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                mProduct = messsageBodyObject;
                LogUtils.i(messsageBodyObject);
                setValue();
                getGowucheProductSize(false, mProduct, 1, false);
            }
        });
    }

    private int getGowucheProductSize(boolean isAdd, GoodsObject product, int size, boolean inInput) {
        //int size = Integer.valueOf(mButSizeTxView.getText().toString());
        if (product != null) {
            GoodsObject object = mDbAdapter.open().getRecordFromProductId(
                    product.getPvsid());
            int productSize = object.getIntoGouwucheSize();
            if (isAdd) {
                product.setSourceId(5);
                Log.d(CommunityUtils.TAG, "productSize:" + productSize);
                if (productSize != -1) {
                    if (inInput) {
                        //大于2表示是从输入框输入的数量
                        productSize = size;
                    } else {
                        productSize += size;
                    }
                } else {
                    productSize = 1;
                }
                product.setIntoGouwucheSize(productSize);
                int update = mDbAdapter.open().updateGouwuche(
                        product.getPvsid(), CommunityUtils.USER_ID,
                        CommunityTool.saveObject(product));
                if (iChangeProductGouwucheNum != null) {
                    iChangeProductGouwucheNum.change(product);
                }
                if (com.blankj.utilcode.util.AppUtils.isAppDebug())
                    Log.d(CommunityUtils.TAG,
                            "gouwucheListener:" + product.getTitle()
                                    + "update:" + update);
                if (update <= 0) {
                    long value = mDbAdapter.open().insertGouwuche(
                            product.getPvsid(), CommunityUtils.USER_ID,
                            CommunityTool.saveObject(product), product.getProductType());
                    if (com.blankj.utilcode.util.AppUtils.isAppDebug())
                        Log.d(CommunityUtils.TAG,
                                "gouwucheListener:" + product.getTitle()
                                        + "value:" + value);
                }
            }
            if (productSize == 0) {
                boolean value = mDbAdapter.open().deleteTitle(String.valueOf(product.getPvsid()));
            }
            int gouwucheSize = 0;
            ArrayList<GoodsObject> getData = mDbAdapter.getAllData();
            for (int i = 0; i < getData.size(); i++) {
                GoodsObject goodsObject = getData.get(i);
                if (goodsObject.getIsCheck() == 0) {
                    gouwucheSize += goodsObject.getIntoGouwucheSize();
                }
            }
            //Log.d(CommunityUtils.TAG, "activitySize:" + activitySize);
            for (int i = 0; i < ActivityUtils.getActivityList().size(); i++) {
                Activity activity = ActivityUtils.getActivityList().get(i);
                if (activity instanceof AddProductToGouwuche) {
                    AddProductToGouwuche in = (AddProductToGouwuche) activity;
                    in.updateData(gouwucheSize);
                }
            }
            return gouwucheSize;
        }
        return 0;
    }

    private void setValue() {
        GoodsObject tGoodsObject = mDbAdapter.open().getRecordFromProductId(
                mProduct.getPvsid());
        int productSize = tGoodsObject.getIntoGouwucheSize();
        if (productSize != 0) {
            mButSizeTxView.setText("" + productSize);
        } else {
            mButSizeTxView.setText("0");
        }

        mProductTitleView.setText(mProduct.getBaseName());
        price = mProduct.getPrice() / 100f;
        mProductPriceView.setText("￥ " + price);
		/*if (price == 0) {
			mProductPriceView.setVisibility(View.INVISIBLE);
		}*/
        if (mProduct.getOldPrice() == mProduct.getPrice() || mProduct.getOldPrice() == 0) {
            mOriginalPrice.setVisibility(View.INVISIBLE);
        } else {
            mOriginalPrice.setVisibility(View.VISIBLE);
        }
        mOriginalPrice.setText("原价：" + mProduct.getOldPrice() / 100f);
        mOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        if (mProduct.getQuantityAvailable() == 0) {
            mSelectsizeLayout.setVisibility(View.GONE);
            mNoStockView.setVisibility(View.VISIBLE);
        }

        String unit = mProduct.getUnit();
        String brand = mProduct.getBrand();
        String description = mProduct.getDescription();

        if (TextUtils.isEmpty(unit)) {
            mProductUnit.setVisibility(View.GONE);
            unit = "暂无";
        } else {
            mProductUnit.setVisibility(View.VISIBLE);
            mProductUnit.setText("单位:" + unit);
        }

        if (TextUtils.isEmpty(description) || description.equals("null")) {
            mProductDiscription.setVisibility(View.GONE);
        } else {
            mProductDiscription.setVisibility(View.VISIBLE);
            if ("暂无".equals(description)) {
                description = "暂无描述";
            }
            mProductDiscription.setText(description);
        }
        if (TextUtils.isEmpty(brand)) {
            brand = "暂无";
            mProductBrand.setText("品牌: " + brand);
        } else {
            mProductBrand.setText("品牌: " + brand);
        }


        mProductImgIds = mProduct.getpImageList();
        if (mProductImgIds == null || mProductImgIds.size() == 0) {
            ImageView imgView = new ImageView(this);
            imgView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//            imgView.setDefaultImageResId(R.mipmap.zhanweitu2);默认图
            mListImageViews.add(imgView);
        } else {
            mPointsViews = new ImageView[mProductImgIds.size()];
            for (int i = 0; i < mProductImgIds.size(); i++) {
                ImageView imgView = new ImageView(this);
                String imgUrl = CommunityTool.changeImageId(
                        mProductImgIds.get(i).imgid, false, false);
                imgView.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
//                imgView.setDefaultImageResId(R.mipmap.zhanweitu2);默认图
//                imgView.setErrorImageResId(R.mipmap.zhanweitu2);错误图
                Glide.with(this).load(imgUrl).apply(options).into(imgView);
                mListImageViews.add(imgView);
                Log.d(CommunityUtils.TAG, "imgUrl:" + imgUrl);
                // productImgs.add(imgUrl);

                ImageView imageView = new ImageView(this);
                ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                imageView.setPadding(10, 0, 10, 0);
                imageView.setMaxWidth(47);
                imageView.setAdjustViewBounds(true);
                imageView.setLayoutParams(lp);
                mPointsViews[i] = imageView;
                if (i == 0) {
                    mPointsViews[i]
                            .setImageResource(R.mipmap.guide_selected);
                } else {
                    mPointsViews[i]
                            .setImageResource(R.mipmap.guide_unselected);
                }
                mViewGroup.addView(mPointsViews[i]);
            }
            if (mProductImgIds.size() == 1) {
                mViewGroup.setVisibility(View.INVISIBLE);
            }
        }

        mImgsPager.setAdapter(new ImageViewsViewPagerAdapter(this,
                mListImageViews));

        ProductFavorite favorite = mDbAdapter.getFavoriteFromId(mProduct
                .getPvsid());
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < mPointsViews.length; i++) {
            if (position == i) {
                mPointsViews[i].setImageResource(R.mipmap.guide_selected);
            } else {
                mPointsViews[i].setImageResource(R.mipmap.guide_unselected);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void addingGouwuche(int size, boolean isInput) {
        String vt = mButSizeTxView.getText().toString();
        if (TextUtils.isEmpty(vt)) {
            return;
        }
        int sizes = Integer.parseInt(vt);
        int quantityAvailable = mProduct.getQuantityAvailable();
        GoodsObject object = mDbAdapter.open().getRecordFromProductId(
                mProduct.getPvsid());
        int productSize = object.getIntoGouwucheSize();
		/*if (price == 0 && (sizes > 1 || productSize > 0)) {
			T.show(GoodsDetailsActivity.this, "亲，此活动只限购一件哦!");
			return;
		}*/
        int limit = sizes;
        if (limit > 99) {
            size = 99;
            //return;
        }
        if (limit > quantityAvailable) {
            size = quantityAvailable;
            ToastUtils.showShort("亲，商品库存只有" + quantityAvailable + "件哦!");
        }
        if (productSize > 99) {
            ToastUtils.showShort("亲，购买数量已达到最大值");
            size = 99;
        }
        getGowucheProductSize(true, mProduct, size, isInput);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, MainActivity.class);
        switch (v.getId()) {
		/*case R.id.join_shopping:
			addingGouwuche();
			break;*/
            case R.id.min_btn:
                String str = mButSizeTxView.getText().toString();
                if (!TextUtils.isEmpty(str)) {
                    int minValue = Integer.valueOf(str);
                    if (minValue > 0) {
                        minValue--;
                        mButSizeTxView.setText("" + minValue);
                        addingGouwuche(-1, false);
                    } else {
                        ToastUtils.showShort("商品不能再减少了哦!");
                    }
                } else {
                    ToastUtils.showShort("亲，您选择的商品数量为0哦!");
                }
                StatisticsConstant.getInstance().ClickActionParams(29, 103, String.valueOf(mProduct.getPvsid()));
                break;
            case R.id.add_btn:
                String str1 = mButSizeTxView.getText().toString();
                if (!TextUtils.isEmpty(str1)) {
                    int vailableSize = mProduct.getQuantityAvailable();
                    int size = Integer.valueOf(str1);
                    if (size > 98) {
                        ToastUtils.showShort("亲，购买数量已达到最大值");
                        return;
                    }
                    if (size < vailableSize) {
                        size++;
                        mButSizeTxView.setText("" + size);
                    } else {
                        ToastUtils.showShort("亲，商品库存只有"
                                + vailableSize + "件哦!");
                        return;
                    }
                } else {
                    mButSizeTxView.setText("" + 1);
                }
                addingGouwuche(1, false);
                StatisticsConstant.getInstance().ClickActionParams(28, 103, String.valueOf(mProduct.getPvsid()));
                break;
            default:
                break;
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right,
                               int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > 100)) {

            //T.show(GoodsDetailsActivity.this, "show");

        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > 100)) {

            ///T.show(GoodsDetailsActivity.this, "dismiss")
            String str = mButSizeTxView.getText().toString();
            if (TextUtils.isEmpty(str)) {
                str = "0";
            }
            int size = Integer.parseInt(str);
            if (size > mProduct.getQuantityAvailable()) {
                ToastUtils.showShort("库存不足了，先买这么多吧!");
                size = mProduct.getQuantityAvailable();
                mButSizeTxView.setText(String.valueOf(size));
            }
            addingGouwuche(size, true);
            StatisticsConstant.getInstance().ClickActionParams(44, 103, String.valueOf(mProduct.getPvsid()));
        }
    }

    @Override
    public void updateData(int productSize) {
        if (productSize > 0) {
            EventBusManager.post(new TabNumberChangedEvent(2, productSize));
        }
    }
}
